package com.gqj.elec.service.impl;

import com.gqj.bas.domain.*;
import com.gqj.bas.mapper.*;
import com.gqj.common.constant.UserConstants;
import com.gqj.common.exception.ServiceException;
import com.gqj.common.utils.DateUtils;
import com.gqj.common.utils.SecurityUtils;
import com.gqj.common.utils.StorageUtil;
import com.gqj.common.utils.StringUtils;
import com.gqj.common.utils.bean.BeanValidators;
import com.gqj.common.utils.uuid.HiultraUtil;
import com.gqj.elec.domain.ElecMaterial;
import com.gqj.elec.domain.ElecMaterialRepairdetail;
import com.gqj.elec.domain.ElecWarning;
import com.gqj.elec.domain.ElecWarningDetail;
import com.gqj.elec.mapper.ElecMaterialMapper;
import com.gqj.elec.mapper.ElecMaterialRepairdetailMapper;
import com.gqj.elec.service.IElecMaterialService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Validator;
import java.math.BigDecimal;
import java.util.*;

/**
 * 物资Service业务层处理
 *
 * @author lxq
 * @date 2023-12-17
 */
@Service
public class ElecMaterialServiceImpl implements IElecMaterialService {
    private static final Logger log = LoggerFactory.getLogger(ElecMaterialServiceImpl.class);
    @Autowired
    private ElecMaterialMapper elecMaterialMapper;
    @Autowired
    protected Validator validator;
    @Autowired
    private BasSortMapper basSortMapper;
    @Autowired
    private BasWarehouseMapper basWarehouseMapper;
    @Autowired
    private BasProviderMapper basProviderMapper;
    @Autowired
    private BasUnitMapper basUnitMapper;
    @Autowired
    private BasCabinetMapper basCabinetMapper;
    @Autowired
    private BasCabinetGridMapper basCabinetGridMapper;
    @Autowired
    private ElecMaterialRepairdetailMapper elecMaterialRepairdetailMapper;

    /**
     * 查询物资
     *
     * @param materialId 物资主键
     * @return 物资
     */
    @Override
    public ElecMaterial selectElecMaterialByMaterialId(Long materialId) {
        return elecMaterialMapper.selectElecMaterialByMaterialId(materialId);
    }

    /**
     * 查询物资列表
     *
     * @param elecMaterial 物资
     * @return 物资
     */
    @Override
    public List<ElecMaterial> selectElecMaterialList(ElecMaterial elecMaterial) {
        return elecMaterialMapper.selectElecMaterialList(elecMaterial);
    }

    /**
     * 查询物资列表
     *
     * @param elecMaterial 物资
     * @return 物资
     */
    @Override
    public List<ElecMaterial> selectElecMaterialWarehouseList(ElecMaterial elecMaterial) {
        return elecMaterialMapper.selectElecMaterialWarehouseList(elecMaterial);
    }

    /**
     * 新增物资
     *
     * @param elecMaterial 物资
     * @return 结果
     */
    @Override
    public int insertElecMaterial(ElecMaterial elecMaterial) {
        elecMaterial.setCreateTime(DateUtils.getNowDate());
        elecMaterial.setRfidCode(StorageUtil.getOrderNoTo12());
        //上次检修日期默认为当前新增日期
        elecMaterial.setPreRepairDate(DateUtils.getNowDate());
        return elecMaterialMapper.insertElecMaterial(elecMaterial);
    }

    /**
     * 修改物资
     *
     * @param elecMaterial 物资
     * @return 结果
     */
    @Override
    public int updateElecMaterial(ElecMaterial elecMaterial) {
        elecMaterial.setUpdateTime(DateUtils.getNowDate());
        return elecMaterialMapper.updateElecMaterial(elecMaterial);
    }

    /**
     * 批量删除物资
     *
     * @param materialIds 需要删除的物资主键
     * @return 结果
     */
    @Override
    public int deleteElecMaterialByMaterialIds(Long[] materialIds) {
        return elecMaterialMapper.deleteElecMaterialByMaterialIds(materialIds);
    }

    /**
     * 删除物资信息
     *
     * @param materialId 物资主键
     * @return 结果
     */
    @Override
    public int deleteElecMaterialByMaterialId(Long materialId) {
        return elecMaterialMapper.deleteElecMaterialByMaterialId(materialId);
    }

    /**
     * 校验物资RFID是否唯一
     *
     * @param elecMaterial 物资信息
     * @return 结果
     */
    @Override
    public String checkMaterialRfidUnique(ElecMaterial elecMaterial) {
        Long materialId = StringUtils.isNull(elecMaterial.getMaterialId()) ? -1L : elecMaterial.getMaterialId();
        ElecMaterial info = elecMaterialMapper.checkMaterialRfidUnique(elecMaterial.getRfidCode(), elecMaterial.getMaterialCategory());
        if (StringUtils.isNotNull(info) && info.getMaterialId().longValue() != materialId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验物资编码是否唯一
     *
     * @param elecMaterial 物资信息
     * @return 结果
     */
    @Override
    public String checkMaterialCodeUnique(ElecMaterial elecMaterial) {
        Long materialId = StringUtils.isNull(elecMaterial.getMaterialId()) ? -1L : elecMaterial.getMaterialId();
        ElecMaterial info = elecMaterialMapper.checkMaterialCodeUnique(elecMaterial.getMaterialCode(), elecMaterial.getMaterialCategory());
        if (StringUtils.isNotNull(info) && info.getMaterialId().longValue() != materialId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 导入工器具数据
     *
     * @param materialList    工器具数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importMaterial(List<ElecMaterial> materialList, Boolean isUpdateSupport, String operName, String materialCategory) {
        if (StringUtils.isNull(materialList) || materialList.size() == 0) {
            throw new ServiceException("导入工器具数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ElecMaterial material : materialList) {
            boolean isOperation = true;
            try {
                // 验证是否存在这个工器具
                ElecMaterial m = elecMaterialMapper.checkMaterialCodeUnique(material.getMaterialCode(), "1");
                if (StringUtils.isNull(m)) {
                    BeanValidators.validateWithException(validator, material);
                    material.setMaterialCategory(materialCategory);

                    BasSort sort = basSortMapper.selectBasSortBySortId(material.getSortId());
                    BasWarehouse warehouse = basWarehouseMapper.checkWarehouseNameUnique(material.getWarehouseName());
                    BasCabinet cabinet = basCabinetMapper.selectBasCabinetByCabinetId(material.getCabinetId());
                    BasCabinetGrid grid = basCabinetGridMapper.selectBasCabinetGridByGridId(material.getGridId());
                    BasProvider provider = basProviderMapper.selectBasProviderByProviderId(material.getProviderId());
                    BasUnit unit = basUnitMapper.checkUnitNameUnique(material.getUnitName());

                    if (null == warehouse) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、库房 " + material.getWarehouseName() + " 不存在");
                        isOperation = false;
                    }
//                    } else if (null == cabinet) {
//                        failureNum++;
//                        failureMsg.append("<br/>" + failureNum + "、柜架编号" + material.getCabinetId() + " 不存在");
//                        isOperation = false;
//                    } else if (cabinet.getWarehouseId() != warehouse.getWarehouseId()) {
//                        failureNum++;
//                        failureMsg.append("<br/>" + failureNum + "、柜架编号" + material.getCabinetId() + " 不属于库房：" + material.getWarehouseName());
//                        isOperation = false;
//                    } else if (null == grid) {
//                        failureNum++;
//                        failureMsg.append("<br/>" + failureNum + "、层格编号" + material.getGridId() + " 不存在");
//                        isOperation = false;
//                    } else if (grid.getCabinetId() != cabinet.getCabinetId()) {
//                        failureNum++;
//                        failureMsg.append("<br/>" + failureNum + "、层格编号" + material.getCabinetId() + " 不属于柜架编码为：" + material.getCabinetId() + "的柜架");
//                        isOperation = false;
//                    } else if (null == provider && null != material.getProviderId()) {
//                        failureNum++;
//                        failureMsg.append("<br/>" + failureNum + "、供应商编号" + material.getProviderId() + " 不存在");
//                        isOperation = false;
//                    } else if (null == unit && null != material.getUnitName() && !"".equals(material.getUnitName())) {
//                        failureNum++;
//                        failureMsg.append("<br/>" + failureNum + "、计量单位" + material.getUnitName() + " 不存在");
//                        isOperation = false;
//                    } else if (null != material.getRfidCode() && !"".equals(material.getRfidCode())) {
//                        if (UserConstants.NOT_UNIQUE.equals(this.checkMaterialRfidUnique(material))) {
//                            failureNum++;
//                            failureMsg.append("<br/>" + failureNum + "、Rfid编码" + material.getRfidCode() + " 已存在");
//                            isOperation = false;
//                        }
//                    }

                    if (isOperation) {
                        material.setCreateBy(operName);
                        material.setMaterialStatus("1");
                        material.setWarehouseId(warehouse.getWarehouseId());
                        material.setRfidCode(StorageUtil.getOrderNoTo12());
                        if (null != unit) {
                            material.setUnitId(unit.getUnitId());
                        }
                        this.insertElecMaterial(material);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、工器具编号 " + material.getMaterialCode() + " 导入成功");
                    }
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, material);
                    material.setMaterialCategory(materialCategory);
                    material.setMaterialId(m.getMaterialId());

                    BasSort sort = basSortMapper.selectBasSortBySortId(material.getSortId());
                    BasWarehouse warehouse = basWarehouseMapper.checkWarehouseNameUnique(material.getWarehouseName());
                    BasCabinet cabinet = basCabinetMapper.selectBasCabinetByCabinetId(material.getCabinetId());
                    BasCabinetGrid grid = basCabinetGridMapper.selectBasCabinetGridByGridId(material.getGridId());
                    BasProvider provider = basProviderMapper.selectBasProviderByProviderId(material.getProviderId());
                    BasUnit unit = basUnitMapper.checkUnitNameUnique(material.getUnitName());
                    if (null == warehouse) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、库房 " + material.getWarehouseName() + " 不存在");
                        isOperation = false;
                    }
//                    if (null == sort) {
//                        failureNum++;
//                        failureMsg.append("<br/>" + failureNum + "、分类编号 " + material.getSortId() + " 不存在");
//                        isOperation = false;
//                    } else if (null == warehouse) {
//                        failureNum++;
//                        failureMsg.append("<br/>" + failureNum + "、库房 " + material.getWarehouseName() + " 不存在");
//                        isOperation = false;
//                    } else if (null == cabinet) {
//                        failureNum++;
//                        failureMsg.append("<br/>" + failureNum + "、柜架编号" + material.getCabinetId() + " 不存在");
//                        isOperation = false;
//                    } else if (cabinet.getWarehouseId() != warehouse.getWarehouseId()) {
//                        failureNum++;
//                        failureMsg.append("<br/>" + failureNum + "、柜架编号" + material.getCabinetId() + " 不属于库房：" + material.getWarehouseName());
//                        isOperation = false;
//                    } else if (null == grid) {
//                        failureNum++;
//                        failureMsg.append("<br/>" + failureNum + "、层格编号" + material.getGridId() + " 不存在");
//                        isOperation = false;
//                    } else if (grid.getCabinetId() != cabinet.getCabinetId()) {
//                        failureNum++;
//                        failureMsg.append("<br/>" + failureNum + "、层格编号" + material.getCabinetId() + " 不属于柜架编码为：" + material.getCabinetId() + "的柜架");
//                        isOperation = false;
//                    } else if (null == provider && null != material.getProviderId()) {
//                        failureNum++;
//                        failureMsg.append("<br/>" + failureNum + "、供应商编号" + material.getProviderId() + " 不存在");
//                        isOperation = false;
//                    } else if (null == unit && null != material.getUnitName() && !"".equals(material.getUnitName())) {
//                        failureNum++;
//                        failureMsg.append("<br/>" + failureNum + "、计量单位" + material.getUnitName() + " 不存在");
//                        isOperation = false;
//                    } else if (null != material.getRfidCode() && !"".equals(material.getRfidCode())) {
//                        if (UserConstants.NOT_UNIQUE.equals(this.checkMaterialRfidUnique(material))) {
//                            failureNum++;
//                            failureMsg.append("<br/>" + failureNum + "、Rfid：" + material.getRfidCode() + " 已存在");
//                            isOperation = false;
//                        }
//                    }

                    if (isOperation) {
                        material.setUpdateBy(operName);
                        material.setWarehouseId(warehouse.getWarehouseId());
                        if (null != unit) {
                            material.setUnitId(unit.getUnitId());
                        }
                        this.updateElecMaterial(material);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、工器具编号 " + material.getMaterialCode() + " 更新成功");
                    }
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、工器具编号 " + material.getMaterialCode() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、工器具编号 " + material.getMaterialCode() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 导入备品备件数据
     *
     * @param materialList    备品备件数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importSpare(List<ElecMaterial> materialList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(materialList) || materialList.size() == 0) {
            throw new ServiceException("导入备品备件数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ElecMaterial material : materialList) {
            boolean isOperation = true;
            try {
                // 验证是否存在这个工器具
                ElecMaterial m = elecMaterialMapper.checkMaterialCodeUnique(material.getMaterialCode(), "3");
                if (StringUtils.isNull(m)) {
                    BeanValidators.validateWithException(validator, material);
                    material.setMaterialCategory("3");

                    BasSort sort = basSortMapper.selectBasSortBySortId(material.getSortId());
                    BasWarehouse warehouse = basWarehouseMapper.checkWarehouseNameUnique(material.getWarehouseName());
                    BasCabinet cabinet = basCabinetMapper.selectBasCabinetByCabinetId(material.getCabinetId());
                    BasCabinetGrid grid = basCabinetGridMapper.selectBasCabinetGridByGridId(material.getGridId());
                    BasProvider provider = basProviderMapper.selectBasProviderByProviderId(material.getProviderId());
                    BasUnit unit = basUnitMapper.checkUnitNameUnique(material.getUnitName());
                    if (null == sort) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、分类编号 " + material.getSortId() + " 不存在");
                        isOperation = false;
                    } else if (null == warehouse) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、库房 " + material.getWarehouseName() + " 不存在");
                        isOperation = false;
                    } else if (null == cabinet) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、柜架编号" + material.getCabinetId() + " 不存在");
                        isOperation = false;
                    } else if (cabinet.getWarehouseId() != warehouse.getWarehouseId()) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、柜架编号" + material.getCabinetId() + " 不属于库房：" + material.getWarehouseName());
                        isOperation = false;
                    } else if (null == grid) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、层格编号" + material.getGridId() + " 不存在");
                        isOperation = false;
                    } else if (grid.getCabinetId() != cabinet.getCabinetId()) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、层格编号" + material.getCabinetId() + " 不属于柜架编码为：" + material.getCabinetId() + "的柜架");
                        isOperation = false;
                    } else if (null == provider && null != material.getProviderId()) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、供应商编号" + material.getProviderId() + " 不存在");
                        isOperation = false;
                    } else if (null == unit && null != material.getUnitName() && !"".equals(material.getUnitName())) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、计量单位" + material.getUnitName() + " 不存在");
                        isOperation = false;
                    } else if (null != material.getRfidCode() && !"".equals(material.getRfidCode()) && "1".equals(material.getSparePartType())) {
                        if (UserConstants.NOT_UNIQUE.equals(this.checkMaterialRfidUnique(material))) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、Rfid编码" + material.getRfidCode() + " 已存在");
                            isOperation = false;
                        }
                    }

                    if (isOperation) {
                        material.setCreateBy(operName);
                        material.setMaterialStatus("0");
                        material.setWarehouseId(warehouse.getWarehouseId());
                        if (null != unit) {
                            material.setUnitId(unit.getUnitId());
                        }
                        this.insertElecMaterial(material);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、工器具编号 " + material.getMaterialCode() + " 导入成功");
                    }
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, material);
                    material.setMaterialCategory("3");
                    material.setMaterialId(m.getMaterialId());

                    BasSort sort = basSortMapper.selectBasSortBySortId(material.getSortId());
                    BasWarehouse warehouse = basWarehouseMapper.checkWarehouseNameUnique(material.getWarehouseName());
                    BasCabinet cabinet = basCabinetMapper.selectBasCabinetByCabinetId(material.getCabinetId());
                    BasCabinetGrid grid = basCabinetGridMapper.selectBasCabinetGridByGridId(material.getGridId());
                    BasProvider provider = basProviderMapper.selectBasProviderByProviderId(material.getProviderId());
                    BasUnit unit = basUnitMapper.checkUnitNameUnique(material.getUnitName());
                    if (null == sort) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、分类编号 " + material.getSortId() + " 不存在");
                        isOperation = false;
                    } else if (null == warehouse) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、库房 " + material.getWarehouseName() + " 不存在");
                        isOperation = false;
                    } else if (null == cabinet) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、柜架编号" + material.getCabinetId() + " 不存在");
                        isOperation = false;
                    } else if (cabinet.getWarehouseId() != warehouse.getWarehouseId()) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、柜架编号" + material.getCabinetId() + " 不属于库房：" + material.getWarehouseName());
                        isOperation = false;
                    } else if (null == grid) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、层格编号" + material.getGridId() + " 不存在");
                        isOperation = false;
                    } else if (grid.getCabinetId() != cabinet.getCabinetId()) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、层格编号" + material.getCabinetId() + " 不属于柜架编码为：" + material.getCabinetId() + "的柜架");
                        isOperation = false;
                    } else if (null == provider && null != material.getProviderId()) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、供应商编号" + material.getProviderId() + " 不存在");
                        isOperation = false;
                    } else if (null == unit && null != material.getUnitName() && !"".equals(material.getUnitName())) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、计量单位" + material.getUnitName() + " 不存在");
                        isOperation = false;
                    } else if (null != material.getRfidCode() && !"".equals(material.getRfidCode()) && "1".equals(material.getSparePartType())) {
                        if (UserConstants.NOT_UNIQUE.equals(this.checkMaterialRfidUnique(material))) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、Rfid：" + material.getRfidCode() + " 已存在");
                            isOperation = false;
                        }
                    }

                    if (isOperation) {
                        material.setUpdateBy(operName);
                        material.setWarehouseId(warehouse.getWarehouseId());
                        if (null != unit) {
                            material.setUnitId(unit.getUnitId());
                        }
                        this.updateElecMaterial(material);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、工器具编号 " + material.getMaterialCode() + " 更新成功");
                    }
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、工器具编号 " + material.getMaterialCode() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、工器具编号 " + material.getMaterialCode() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 查询分类统计信息
     */
    @Override
    public Map<String, Object> querySortStatistics(ElecMaterial elecMaterial) {
        Map<String, Object> map = new HashMap<String, Object>();

        List<Map<String, Object>> li = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> liQ = new ArrayList<Map<String, Object>>();
        Integer statisticsDataNum = elecMaterial.getStatisticsDataNum();

        li = elecMaterialMapper.selectSortMaterialNum(elecMaterial);
        if (null != li && li.size() > statisticsDataNum) {
            for (int i = 0; i < statisticsDataNum; i++) {
                Map<String, Object> mapTemp = li.get(i);
                liQ.add(mapTemp);
            }
            Long num = new Long(0);
            for (int i = statisticsDataNum; i < li.size(); i++) {
                Map<String, Object> mapTemp = li.get(i);
                Long numTemp = new Long(mapTemp.get("value").toString());
                num = num + numTemp;
            }
            Map<String, Object> mapTempT = new HashMap<String, Object>();
            mapTempT.put("name", "其他");
            mapTempT.put("value", num);
            liQ.add(mapTempT);
            String[] sortArr = new String[liQ.size()];
            Long[] sortNum = new Long[liQ.size()];

            for (int i = 0; i < liQ.size(); i++) {
                Map<String, Object> mapT = liQ.get(i);
                String sortName = (String) mapT.get("name");
                Long sortValue = (Long) mapT.get("value");
                sortArr[i] = sortName;
                sortNum[i] = sortValue;
            }

            map.put("sortNum", sortNum);
            map.put("sortArr", sortArr);
        } else {
            String[] sortArr = new String[li.size()];
            Long[] sortNum = new Long[li.size()];

            for (int i = 0; i < li.size(); i++) {
                Map<String, Object> mapT = li.get(i);
                String sortName = (String) mapT.get("name");
                Long sortValue = (Long) mapT.get("value");
                sortArr[i] = sortName;
                sortNum[i] = sortValue;
            }

            map.put("sortNum", sortNum);
            map.put("sortArr", sortArr);
        }

        return map;
    }

    /**
     * 查询库房统计信息
     */
    @Override
    public Map<String, Object> queryWarehouseStatistics(ElecMaterial elecMaterial) {
        Map<String, Object> map = new HashMap<String, Object>();

        List<Map<String, Object>> li = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> liQ = new ArrayList<Map<String, Object>>();
        Integer statisticsDataNum = elecMaterial.getStatisticsDataNum();

        li = elecMaterialMapper.selectWarehouseMaterialNum(elecMaterial);
        if (null != li && li.size() > statisticsDataNum) {
            for (int i = 0; i < statisticsDataNum; i++) {
                Map<String, Object> mapTemp = li.get(i);
                liQ.add(mapTemp);
            }
            Long num = new Long(0);
            for (int i = statisticsDataNum; i < li.size(); i++) {
                Map<String, Object> mapTemp = li.get(i);
                Long numTemp = new Long(mapTemp.get("value").toString());
                num = num + numTemp;
            }
            Map<String, Object> mapTempT = new HashMap<String, Object>();
            mapTempT.put("name", "其他");
            mapTempT.put("value", num);
            liQ.add(mapTempT);

            map.put("warehouseList", liQ);
        } else {
            map.put("warehouseList", li);
        }

        return map;
    }

    /**
     * 查询货架物资状态数量
     */
    @Override
    public Map<String, Object> selectMaterialStatusNum() {
        String[] cabinetInfo = elecMaterialMapper.selectCabinetInfo();

        ElecMaterial elecMaterial = new ElecMaterial();
        elecMaterial.setMaterialStatus("0");
        List<Map<String, Object>> li0 = elecMaterialMapper.selectMaterialStatusNum(elecMaterial);
        long[] lrNum = new long[cabinetInfo.length];
        for (int i = 0; i < cabinetInfo.length; i++) {
            for (Map<String, Object> map : li0) {
                String name = (String) map.get("name");
                long value = (long) map.get("value");

                if (cabinetInfo[i].equals(name)) {
                    lrNum[i] = value;
                }
            }
        }

        elecMaterial.setMaterialStatus("1");
        List<Map<String, Object>> li1 = elecMaterialMapper.selectMaterialStatusNum(elecMaterial);
        long[] zkNum = new long[cabinetInfo.length];
        for (int i = 0; i < cabinetInfo.length; i++) {
            for (Map<String, Object> map : li1) {
                String name = (String) map.get("name");
                long value = (long) map.get("value");

                if (cabinetInfo[i].equals(name)) {
                    zkNum[i] = value;
                }
            }
        }

        elecMaterial.setMaterialStatus("2");
        List<Map<String, Object>> li2 = elecMaterialMapper.selectMaterialStatusNum(elecMaterial);
        long[] ckNum = new long[cabinetInfo.length];
        for (int i = 0; i < cabinetInfo.length; i++) {
            for (Map<String, Object> map : li2) {
                String name = (String) map.get("name");
                long value = (long) map.get("value");

                if (cabinetInfo[i].equals(name)) {
                    ckNum[i] = value;
                }
            }
        }

        elecMaterial.setMaterialStatus("3");
        List<Map<String, Object>> li3 = elecMaterialMapper.selectMaterialStatusNum(elecMaterial);
        long[] ykcNum = new long[cabinetInfo.length];
        for (int i = 0; i < cabinetInfo.length; i++) {
            for (Map<String, Object> map : li3) {
                String name = (String) map.get("name");
                long value = (long) map.get("value");

                if (cabinetInfo[i].equals(name)) {
                    ykcNum[i] = value;
                }
            }
        }

        elecMaterial.setMaterialStatus("4");
        List<Map<String, Object>> li4 = elecMaterialMapper.selectMaterialStatusNum(elecMaterial);
        long[] kchjNum = new long[cabinetInfo.length];
        for (int i = 0; i < cabinetInfo.length; i++) {
            for (Map<String, Object> map : li3) {
                String name = (String) map.get("name");
                long value = (long) map.get("value");

                if (cabinetInfo[i].equals(name)) {
                    kchjNum[i] = value;
                }
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("cabinet", cabinetInfo);
        map.put("lrNum", lrNum);
        map.put("zkNum", zkNum);
        map.put("ckNum", ckNum);
        map.put("ykcNum", ykcNum);
        map.put("kchjNum", kchjNum);
        return map;
    }

    /**
     * 查询类别统计信息
     */
    @Override
    public Integer[] selectCategoryNum(ElecMaterial elecMaterial) {
        return elecMaterialMapper.selectCategoryNum();
    }

    /**
     * 通过标签号查询物资
     *
     * @param rfidCcde 标签号
     * @return 物资
     */
    @Override
    public ElecMaterial selectElecMaterialByRfidCode(String rfidCcde) {
        return elecMaterialMapper.queryByRfidCode(rfidCcde);
    }

    /**
     * 查询维修
     *
     * @param elecMaterial 物资
     * @return 物资集合
     */
    @Override
    public List<ElecMaterial> listRepair(ElecMaterial elecMaterial) {
        List<ElecMaterial> elecMaterialList = elecMaterialMapper.selectElecMaterialList(elecMaterial);
        List<ElecMaterial> overdueMaterials = new ArrayList<>();
        Date nowDate = new Date();

        for (ElecMaterial material : elecMaterialList) {
            if (null != material.getRepairCycle() && 0 != material.getRepairCycle()) {
                int difference = HiultraUtil.differentDays(material.getPreRepairDate(), nowDate);

                if (difference != 0) {
                    // 将变量转换类型
                    BigDecimal differenceTemp = new BigDecimal(difference);
                    BigDecimal san = new BigDecimal(30);
                    // 求出到目前为止已经过了几个月了
                    BigDecimal month = differenceTemp.divide(san, 2, BigDecimal.ROUND_HALF_UP);

                    BigDecimal repairperiodTemp = new BigDecimal(material.getRepairCycle());
                    // 差值比维修周期大了 就是要维修了
                    if (month.compareTo(repairperiodTemp) > 0) {
                        overdueMaterials.add(material);
                    }
                }
            }
        }
        return overdueMaterials;
    }

    /**
     * 批量检修物资
     *
     * @param materialIds 需要检修的物资主键集合
     * @return 结果
     */
    @Override
    public int repairMaterial(Long[] materialIds){
        int i = 0;
        for (Long id : materialIds ) {
            ElecMaterial elecMaterial = elecMaterialMapper.selectElecMaterialByMaterialId(id);
            if (null == elecMaterial) {
                throw new ServiceException("未找到该物资");
            }
            //修改物资上次检修时间为现在
            elecMaterial.setPreRepairDate(DateUtils.getNowDate());
            elecMaterialMapper.updateElecMaterial(elecMaterial);

            //记录检修记录
            ElecMaterialRepairdetail elecMaterialRepairdetail = new ElecMaterialRepairdetail();
            elecMaterialRepairdetail.setMaterialId(elecMaterial.getMaterialId());
            elecMaterialRepairdetail.setCreateBy(SecurityUtils.getUsername());
            elecMaterialRepairdetail.setRepairDate(DateUtils.getNowDate());
            elecMaterialRepairdetail.setCreateTime(DateUtils.getNowDate());
            elecMaterialRepairdetail.setUpdateBy(SecurityUtils.getUsername());
            elecMaterialRepairdetail.setUpdateTime(DateUtils.getNowDate());
            i = elecMaterialRepairdetailMapper.insertElecMaterialRepairdetail(elecMaterialRepairdetail);
        }
        return  i;
    }
}
